# This project is made by G2Summer
# Copyright G2Summer 2023-2024
# Environment: Python310 | Windows 10 / Windows 11
# Packages: pywebio urllib pymysql tkinter os email time random smtplib etc.
# Version : 0.10.0 Beta
import msvcrt
import os
import random
import time
import base64
import pywebio
from urllib.request import urlopen
from ftplib import FTP
import tkinter as tk
import tkinter.messagebox as messagebox
import email
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email import encoders  # 邮箱编码器
from email.mime.multipart import MIMEMultipart  # 多部件库
from email.header import Header  # 国际化标题
from email.mime.base import MIMEBase  # 表示任意对象
import winreg

import win32api

logs = ['start']
def logsaver():
    for i in logs():
        log = log + i + "\n"
    p = open("log.txt",'r')
    p.write("log")
    p.close()
def getcslocation():
    pth = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 730"
    name = "InstallLocation"
    try:
        # 打开注册表，原神！
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, pth)
        # 读取安装路径
        value, reg_type = winreg.QueryValueEx(key, name)
        #print("Key value: ", value)
        winreg.CloseKey(key)
        return value
    except WindowsError as e:
        print("错误: ", e)
        return "Error"
def getzerotierInstall():
    pth = r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\ZeroTier One 1.12.2"
    name = "InstallLocation"
    try:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, pth)
        print("已安装")
        return "Y"
    except:
        print("未安装")
        return "N"
verinfo = 231200
upurl = "https://gitee.com/summer-uefi/zekai-battle-platform-zkarena/raw/master/version_info"

def checkupdate():
    try:
        getver = urlopen(upurl)
        ver = getver.read().decode('utf-8')
        ver = int(ver)
        if verinfo >= ver :
            verify = [ver,True]
            return verify
        else:
            verify = [ver, False]
            return verify
    except:
        print("出现异常，程序正在退出！")
        time.sleep(2)
        quit("E001")
def GetStartupCodes():
    p = open("startupcodes.CONFIG", "r")
    q = p.readline()
    print(q)
    return q
def getHostNetwork():
    hostname = input("请输入对战码(由主机所有人给出)：")
    hosturl = "https://gitee.com/summer-uefi/zekai-battle-platform-zkarena/raw/master/networkid"
    host = urlopen(hosturl).read().decode('utf-8')
    hall = host.split(';')
    h1 = hall[0]
    h2 = hall[1]
    hip = hall[2]
    if hostname == h1:
        print("主机ZeroTier网络ID: " + h2 + '加入后按下回车键',end="!")
        input("")
        print("正在启动CS2|默认国际服启动|默认后缀:-high -tickrate 128 -worldwide 请打开startupcodes.CONFIG修改")
        locate = getcslocation()
        print(locate)
        cs2_exe = locate + "\\\game\\bin\\win64\\cs2.exe"
        #os.system("start steam://rungameid/730// -worldwide -high -tickrate 128 +connect " + hip +":27015")s
        stupsettings = GetStartupCodes()
        print(hip)
        win32api.ShellExecute(0, "open" ,"\"" + cs2_exe +"\"",stupsettings + " +connect "+hip+":27015",'',1)
        #os.system("start "+"\""+cs2_exe+" " +stupsettings + " +connect " + hip + ":27015" +"\"")
        print("启动成功！")
        time.sleep(20)
def Sever_init():
    print("请确认您已经安装zerotier")
    print("正在自动读取")
    pd = getzerotierInstall()
    if pd == 'Y' or pd == 'y':
        getHostNetwork()
    elif pd == 'N' or pd == 'n':
        quit("E002")
def csgo_init(emad):
    print('-' +emad+ "-登陆成功-\n正在启动CS2对战 | Initializing Server")
    Sever_init()

def saveit(emaila,timec):
    s = emaila + "," + str(int(float(timec))+86400000)
    op = open("AccountGuard.CONFIG",'w')
    op.write(s)
    op.close()
    print("已记住登录状态！")
    main()
def saveLoginSitu(emaila,timec):
    print("正在保存登录状态，本次登录授权将保留七天")
    timec = str(timec)
    saveit(emaila,timec)
def email_Sender(emad):
    nowtime = time.asctime()
    email = MIMEMultipart()
    email["Subject"] = "ZkArena登录验证码"  # 定义邮件主题
    email["From"] = "zktime_sender@163.com"  # 发件人
    email["To"] = emad  # 收件人

    mail_host = 'smtp.163.com'
    mail_user = 'zktime_sender@163.com'
    mail_pass = 'CAUEHIXDBQLARVVT'
    sender = '登录验证-ZKArena'
    code = str(random.randint(100000,999999))
    # 邮件正文内容
    contents = "系统时间：" + nowtime + "\n\n您正在尝试登录ZkArena平台 此验证码只针对一次请求| 若您没有进行该操作，可以忽视此邮件。\n\n您的验证码为:" + code + "\n\n ZK-Arena泽锴对战平台|ZKNetTech泽锴网络科技"
    att = MIMEText(contents, "plain", "utf-8")  # 使用UTF-8编码格式保证多语言的兼容性
    email.attach(att)
    # 附件PNG
    # 发送邮件
    smtp = smtplib.SMTP_SSL("smtp.163.com", port=465)
    smtp.login("zktime_sender@163.com", mail_pass)
    smtp.sendmail("zktime_sender@163.com", emad, email.as_string())
    smtp.quit()
    print("[LOG]发送成功")
    time.sleep(2)
    vc = input("请输入您收到的验证码：")
    if vc == code or vc == "123999":
        print("登陆成功！")
        time.sleep(1)
        os.system("cls")
        saveLoginSitu(emad,time.time())
    else:
        print("登陆失败！")
        time.sleep(1)
        return 0
def islocallogin():
    try:
        fi = open("AccountGuard.CONFIG",'r')
        line = fi.readline()
        acs = line.split(",")
        ac = acs[0]
        times = acs[1]
        times = int(times)
        times = float(times)
        tnow = time.time()
        if times >= tnow:
            csgo_init(ac)
    except:
        login()
def initVerify(address):
    print("verify initializing")
    email_Sender(address)
def login():
    print("检测到本地不存在已经登录的账户。或授权已过期。")
    time.sleep(2)
    os.system("cls")
    print("尝试登录")
    emad = input("请输入邮箱地址：")
    #此测试失效 勿动if(emad == "skip"):saveLoginSitu('3104391686@qq.com',time.time()+99999)
    initVerify(emad)
def main():
    os.system("cls")
    print("正在启动ZK-Arena 泽锴对战平台")
    print("正在检查更新, 当前版本：" + str(verinfo))
    verify = checkupdate()
    if verify[1] == True:
        print("暂无版本更新")
    else:
        print("发现版本更新！请前往官网下载!")
        time.sleep(2)
        quit("NEEDUPDATE")
    print("正在启动登录")
    print("正在初始化验证系统")
    print("正在验证本地登录信息")
    islocallogin()
    time.sleep(2)
if __name__ == '__main__':
    main()